package com.app.scale.scale;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.scale.R;
import com.app.scale.basis.BasisActivity;
import com.app.scale.basis.BasisApp;
import com.app.scale.basis.Constants;
import com.app.scale.bean.GoodsListBean;
import com.app.scale.bean.GoodsListData;
import com.app.scale.bean.LoginBean;
import com.app.scale.bean.SupplierListData;
import com.app.scale.bean.UserInfoBean;
import com.app.scale.camera.SlientCamera;
import com.app.scale.dashboard.DashboardView3;
import com.app.scale.greendao.GreenDaoUtils;
import com.app.scale.login.LoginActivity;
import com.app.scale.util.MyUtils;
import com.app.scale.util.ReadCardUtils;
import com.app.scale.util.SoftKeyboardUtil;
import com.app.scale.view.AddPeopleDialog;
import com.app.scale.view.BaseEditDialog;
import com.app.scale.view.MyEditText;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.vandin.weigher.sdk.connector.IWeigh;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import my.ActivityTool;
import my.DialogUtils;
import my.LogUtil;
import my.MathUtils;
import my.http.MyHttpUtils;

public class ScaleActivity extends BasisActivity implements ScaleView{


    private List<UserInfoBean> jijiayuanIdList = new ArrayList<>();
    UserInfoBean curJiJiaYuan; // 计价员的bean

    ScalePresenter presenter;
    @BindView(R.id.dashboardView)
    DashboardView3 dashboardView;
    @BindView(R.id.text_title_right_role)
    TextView tvRole;

    @BindView(R.id.text_title_right_name)
    TextView tvName;

    @BindView(R.id.edit_code)
    EditText edit_code;

    @BindView(R.id.edit_price)
    MyEditText edit_price;

    private SupplierListData supplierLData;
    long curTimeStamp;

    private IWeigh IControl;


    /**
     * 下面是  idcard的字段
     */
    @BindView(R.id.text_id_car_name)
    TextView text_id_car_name;                  //供应商姓名
    @BindView(R.id.text_id_car_num)
    TextView text_id_car_num;
    @BindView(R.id.text_id_car_mu)
    TextView text_id_car_mu;
    @BindView(R.id.text_bno)
    TextView text_bno;

    @BindView(R.id.text_yz)           //银针溯源余量
    TextView text_yz;
    @BindView(R.id.text_md)           //牡丹溯源余量
    TextView text_md;
    @BindView(R.id.text_sm)           //寿眉溯源余量
    TextView text_sm;

    @BindView(R.id.edit_yz)  //银针溯源欠量
    EditText edit_yz;
    @BindView(R.id.edit_md)      //牡丹溯源欠量
    EditText edit_md;
    @BindView(R.id.edit_sm)          //寿眉溯源欠量
    EditText edit_sm;


    @BindView(R.id.img_tou_xiang)
    QMUIRadiusImageView imgIcon;
    @BindView(R.id.icon_qrcode)
    ImageView icon_qrcode;
    @BindView(R.id.text_id_car_title)
    TextView text_id_car_title;

    private int needChangePosition = -1;


    /**
     * 下面是 货品资料的界面
     */
    @BindView(R.id.recycle_goods)
    RecyclerView mRecyclerGoods;
    private GoodListAdapter mAdapter;
    GoodsListBean mListBean;
    @BindView(R.id.text_goods_weight)
    TextView text_goods_weight;
    @BindView(R.id.text_goods_num)
    TextView text_goods_num;
    @BindView(R.id.text_goods_total)
    TextView text_goods_total;

    //U口读卡器,类似于外接键盘
    private ReadCardUtils readCardUtils;

    SlientCamera slientCamera;

    @BindView(R.id.switch_con)
    Switch continuitySwitch;
    @BindView(R.id.switch_sub_img)
    Switch subMitImgSwitch;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.scale_activity);
        setTitleBg(R.color.transparent);

        presenter = new ScalePresenterImpl(this);
        IControl = presenter.getIWeigh(mContext);
//        mItt = presenter.getTimetoTakePic(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerGoods.setLayoutManager(layoutManager);

        edit_price.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
                } else {
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                }
            }
        });
        edit_price.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mListBean == null || mListBean.getList().size()==0) return;
                if(s.toString().equals("") || TextUtils.isEmpty(s.toString()) || "null".equals(s.toString())){
                    mListBean.changPrice(mContext,"0");
                }else {
                    mListBean.changPrice(mContext,s.toString());
                }
                setListView();
            }
        });

        //读卡器声明
        readCardUtils = new ReadCardUtils();
        initCardReader();

        slientCamera = new SlientCamera(mContext);
        slientCamera.openCamere();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        LoginBean loginBean = LoginBean.getInstance();
        tvRole.setText(loginBean.getUfsName());
        tvName.setText(loginBean.getUname());
        mListBean = new GoodsListBean();
        setListView();
        if(LoginBean.getInstance().canJijia()){
            curJiJiaYuan = UserInfoBean.getAdminInfo();
            edit_price.setEnabled(true);
        }
    }

    @OnClick({R.id.view_yin_zhen,R.id.view_shou_mei,R.id.view_mu_dan,R.id.text_search,R.id.view_price,
            R.id.view_settlement,R.id.view_out,R.id.view_home,R.id.view_all_delete,R.id.view_gua_dan,
            R.id.img_search,R.id.img_tou_xiang,R.id.icon_qrcode,R.id.view_reset})
    public void btnOnClick(View v){
        switch (v  .getId()){
            case R.id.text_search:          //获取供应商
                if(TextUtils.isEmpty(edit_code.getText().toString())){
                    showToast("请输入供应商号码");
                    return;
                }
                presenter.getSupplierInfoByCode(this,edit_code.getText().toString());
                break;
            case R.id.img_search:          //扫描二维码
//                ActivityTool.skipActivityForResult(mContext,ImageGridActivity.class,Constants.IMGPICK);
                ActivityTool.skipActivityForResult(mContext, CaptureActivity.class,Constants.QCORDRESULT);
                break;
            case R.id.view_yin_zhen:        //银针按钮
                if(this.supplierLData == null){
                    showToast("供应商请刷卡!");
                    return;
                }
                presenter.getGoodsListByFsg(this,Constants.YZ);
                break;
            case R.id.view_shou_mei:        //寿眉按钮
                if(this.supplierLData == null){
                    showToast("供应商请刷卡!");
                    return;
                }
                presenter.getGoodsListByFsg(this,Constants.SM);
                break;
            case R.id.view_mu_dan:      //牡丹按钮
                if(this.supplierLData == null){
                    showToast("供应商请刷卡!");
                    return;
                }
                presenter.getGoodsListByFsg(this,Constants.MD);
                break;
            case R.id.view_price:       //请输入单价按钮
                if(!edit_price.isEnabled()){
                    presenter.isJiJiaYuan(this,jijiayuanIdList);
                }else {
                    SoftKeyboardUtil.showSoftInput(mContext,edit_price);
                }
                break;
            case R.id.view_out:       //换班
                LoginActivity.toLoginAllClear(mContext);
                break;
            case R.id.view_reset:       //置零
//                LoginActivity.toLoginAllClear(mContext);
                break;
            case R.id.view_home:       //返回
                finish();
                break;
            case R.id.view_all_delete:       //删除
                DialogUtils.showWarningDialog(mContext,"是否确定删除？","删除",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        mListBean.deleteCheckList();
                        setListView();
                    }
                });

                break;
            case R.id.view_gua_dan:       //挂单
                DialogUtils.showWarningDialog(mContext,"是否确定挂单？","挂单",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        mListBean.guaDanCheckList();
                        settlement();
                    }
                });
                break;
            case R.id.view_settlement:       //结算
                DialogUtils.showWarningDialog(mContext,"是否确定结算？","立即结算",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        settlement();
                    }
                });
                break;
            case R.id.img_tou_xiang:       //头像
                if(this.supplierLData == null){
                    AddPeopleDialog dialog= new AddPeopleDialog(mContext, new AddPeopleDialog.onPeopleStatusEditListener() {

                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onToast(String mes) {
                            showToast(mes);
                        }
                    });
                    dialog.show();
                }
                break;
            case R.id.icon_qrcode:       //二维码
                //todo
//                if(TextUtils.isEmpty(this.supplierLData.getBno())){
                    BaseEditDialog dialog = new BaseEditDialog(mContext, new BaseEditDialog.OnEditPostListener() {
                        @Override
                        public void onEditPost(String value) {
                            supplierLData.setAutoBno(value);
                            GreenDaoUtils.supplierBeanReplace(supplierLData, new GreenDaoUtils.GreenDaoInserCallBack() {
                                @Override
                                public void onDataInsert(int count) {
                                    presenter.changeSupplierLData(ScaleActivity.this,supplierLData);
                                }
                            });
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    dialog.show();
//                }

                break;

        }
    }

    private void settlement(){
        presenter.settlement(this,mListBean,supplierLData,curJiJiaYuan);
    }

    @Override
    public void settlementSuccess() {
        if(isFinishing())return;
        if(!LoginBean.getInstance().canJijia()){  //4代表管理员，可以直接输入单价
            curJiJiaYuan = null;
            edit_price.setEnabled(false);
        }

        mListBean = new GoodsListBean();
        setListView();

        edit_yz.clearFocus();
        edit_md.clearFocus();
        edit_sm.clearFocus();

        edit_price.getText().clear();
        edit_price.clearFocus();
        edit_code.clearFocus();

        if(!continuitySwitch.isChecked()){
            imgIcon.setImageResource(R.drawable.user_sign_icon_photo);
            icon_qrcode.setVisibility(View.GONE);
            edit_yz.getText().clear();
            edit_md.getText().clear();
            edit_sm.getText().clear();
            text_yz.setText("0");
            text_md.setText("0");
            text_sm.setText("0");
            text_id_car_name.setText(text_id_car_name.getHint());
            text_id_car_num.setText(text_id_car_num.getHint());
            text_id_car_mu.setText(text_id_car_mu.getHint());
            text_bno.setText(text_bno.getHint());
            this.supplierLData = null;
        }

        DialogUtils.showSuccessrDialog(mContext,"提示！","结算成功！");
    }


    /**
     * 获取供应商 数据
     * @param supplierListData
     */
    @Override
    public void getSupplierResult(SupplierListData supplierListData) {
        this.supplierLData = supplierListData;
        curTimeStamp = System.currentTimeMillis();
        switch (supplierListData.getCfs()){
            case "代理商":
                text_id_car_mu.setVisibility(View.GONE);
                text_yz.setVisibility(View.VISIBLE);
                text_md.setVisibility(View.VISIBLE);
                text_sm.setVisibility(View.VISIBLE);
                edit_yz.setEnabled(true);
                edit_md.setEnabled(true);
                edit_sm.setEnabled(true);
                edit_yz.getText().clear();
                edit_md.getText().clear();
                edit_sm.getText().clear();
                edit_yz.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if(supplierLData == null) return;
                        try {
                            String value = s.toString();
                            if(value.equals("")||TextUtils.isEmpty(value) || value.equals("null")){
                                value="0";
                            }
                            supplierLData.setEditTra1(value);
                        }catch (NullPointerException e){
                            supplierLData.setEditTra1("0");
                        }
                    }
                });
                edit_md.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if(supplierLData == null) return;
                        try {
                            String value = s.toString();
                            if(value.equals("")||TextUtils.isEmpty(value) || value.equals("null")){
                                value="0";
                            }
                            supplierLData.setEditTra2(value);
                        }catch (NullPointerException e){
                            supplierLData.setEditTra2("0");
                        }

                    }
                });
                edit_sm.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if(supplierLData == null) return;
                        try {
                            String value = s.toString();
                            if(value.equals("")||TextUtils.isEmpty(value) || value.equals("null")){
                                value="0";
                            }
                            supplierLData.setEditTra3(value);
                        }catch (NullPointerException e){
                            supplierLData.setEditTra3("0");
                        }
                    }
                });
                MyUtils.setDefaultText(text_yz,supplierListData.getTra1(),"0");
                MyUtils.setDefaultText(text_md,supplierListData.getTra2(),"0");
                MyUtils.setDefaultText(text_sm,supplierListData.getTra3(),"0");
                break;
            case "茶农":
                text_id_car_mu.setVisibility(View.VISIBLE);
                text_yz.setVisibility(View.GONE);
                text_md.setVisibility(View.GONE);
                text_sm.setVisibility(View.GONE);
                edit_yz.setEnabled(false);
                edit_md.setEnabled(false);
                edit_sm.setEnabled(false);
                MyUtils.setDefaultText(edit_yz,supplierListData.getTra1(),"0");
                MyUtils.setDefaultText(edit_md,supplierListData.getTra2(),"0");
                MyUtils.setDefaultText(edit_sm,supplierListData.getTra3(),"0");
                break;
        }

        String url = MyHttpUtils.getAbsoluteUrl(supplierListData.getFiles());
        BasisApp.loadImg(mContext,url,imgIcon);
        MyUtils.setNotNullText(text_id_car_name,"姓名: ",supplierListData.getCna());
        MyUtils.setNotNullText(text_id_car_num,"身份证: ",supplierListData.getCno());
        MyUtils.setNotNullText(text_id_car_mu,"亩数: ",supplierListData.getAcr());
        icon_qrcode.setVisibility(View.VISIBLE);
        if(TextUtils.isEmpty(this.supplierLData.getBno())){
            icon_qrcode.setImageResource(R.mipmap.icon_question);
        }else {
            Bitmap bitmap = CodeUtils.createImage(this.supplierLData.getAutoBno(), 80, 80, null);
            icon_qrcode.setImageBitmap(bitmap);
        }
        MyUtils.setNotNullText(text_bno,"大数据溯源码: ",supplierListData.getBno());
        edit_code.getText().clear();

    }

    /**
     * 圆盘秤重的值
     * @param value
     */
    @Override
    public void dashboardViewSetValue(float value) {
        runOnUiThread(new Runnable() {   //执行UI更新
            @Override
            public void run() {
                dashboardView.setValue(value, true, false);
            }
        });
    }


    /**
     * 是否是计价员
     * @param yesOrNo
     */
    @Override
    public void isJiJiaYuan(boolean yesOrNo,UserInfoBean jiJiaYuan) {
        if(isFinishing())return;
        if(yesOrNo){
            edit_price.setEnabled(true);
            curJiJiaYuan = jiJiaYuan;
//            DialogUtils.showSuccessrDialog(mContext,"验证成功",jiJiaYuan.getUfsName()+":"+jiJiaYuan.getUname());
            showToast("验证成功");
        }else {
            edit_price.setEnabled(false);
            edit_price.getText().clear();
            curJiJiaYuan = null;
            DialogUtils.showErrorDialog(mContext,"请刷计价员卡！");
        }
    }

    /**
     * 获取到茶青的list
     * @param goodsListBean  查青List
     * @param fsg  茶青类型
     */
    @Override
    public void getGoodsListResultByFsg(GoodsListBean goodsListBean,String fsg) {
        switch (fsg){
            case Constants.MD:
            case Constants.SM:
            case Constants.YZ:
                presenter.showGoodsOption(mContext,goodsListBean);
                break;
        }
    }

    /**
     * 获取茶青option 的 选择项
     * @param goodsListData
     */
    @Override
    public void getGoodsOptionsResult(GoodsListData goodsListData) {
        if(needChangePosition != -1){
            mListBean.changeBeanByPosition(needChangePosition,goodsListData);
            mAdapter.notifyItemChanged(needChangePosition);
            needChangePosition = -1;
            return;
        }

        if(subMitImgSwitch.isChecked()){
            slientCamera.tackPicture(goodsListData.getGna(),goodsListData.getFsg(),new SlientCamera.OnFileListener() {
                @Override
                public void onResult(File file) {
                    goodsListData.setImgPath(file.getPath());
                }
            }, new SlientCamera.OnUrlListener() {
                @Override
                public void onUrl(String url) {
                    goodsListData.setPath(url);
                    goodsListData.setGwt(""+presenter.getScaleWeight());
                    goodsListData.setGpr("0");
                    mListBean.addListData(goodsListData);
                    edit_price.getText().clear();
                    setListView();
                }
            });
        }else {
            goodsListData.setGwt(""+presenter.getScaleWeight());
            goodsListData.setGpr("0");
            mListBean.addListData(goodsListData);
            edit_price.getText().clear();
            setListView();
        }



    }


    /**
     * 打印机的错误信息
     * @param message
     */
    @Override
    public void printMessage(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(message);
            }
        });
    }

    /**
     * 打印机打印结束
     */
    @Override
    public void printFinish() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissProgress();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.closeIWeigh();
        presenter.ClosePort();
        readCardUtils.removeScanSuccessListener();
        readCardUtils = null;
        slientCamera.onDestroy();
    }


    /**
     * 读卡器初始化
     *  读卡器数据获取
     */
    private void initCardReader() {
        readCardUtils.setReadSuccessListener(new ReadCardUtils.OnReadSuccessListener() {
            @Override
            public void onScanSuccess(String barcode) {
                LogUtil.d("barcode: " + barcode);
                switch (GreenDaoUtils.checkIsUserOrSupplier(barcode)){
                    case "user":
                        presenter.isJiJiaYuan(ScaleActivity.this,jijiayuanIdList,barcode);
                        break;
                    case "supplier":
                        presenter.getSupplierInfoByCode(ScaleActivity.this,barcode);
                        break;
                    case "supplierBno":
                        presenter.getSupplierInfoByBno(ScaleActivity.this, barcode.replace("http//www.fdbcdsj.cn8880/QRHome/Scan/",""));
                        break;
                }
            }
        });
    }

    /**
     * 帮助读卡器
     *  当edittext没有获取焦点的时候   截取数据
     */
    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null){
                readCardUtils.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }



    /**
     * 下面就是 listview的
     */

    @Override
    public void setListView() {
        if (mAdapter == null) {
            mAdapter = new GoodListAdapter();
            mRecyclerGoods.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
            notifyBottonText();
        }
        setEmptyView();
    }

    private void notifyBottonText(){
        text_goods_num.setText(""+mListBean.getList().size());
        text_goods_total.setText(mListBean.getAllTotal());
        text_goods_weight.setText(mListBean.getAllWeight()+"斤");
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.GONE);
        }
    }


    public class GoodListAdapter extends RecyclerView.Adapter<GoodListAdapter.ViewHolder> {

        public GoodListAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.scale_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_weight)
            public TextView text_weight;
            @BindView(R.id.text_price)
            public TextView text_price;
            @BindView(R.id.text_money)
            public TextView text_money;
            @BindView(R.id.img_icon)
            public ImageView img_icon;
            @BindView(R.id.img_change)
            public ImageView img_change;
            @BindView(R.id.btn_kou)
            public TextView btn_kou;
            @BindView(R.id.btn_chen)
            public TextView btn_chen;
            @BindView(R.id.btn_add)
            public TextView btn_add;
            @BindView(R.id.text_gua)
            public TextView text_gua;
            @BindView(R.id.text_pwt)
            public TextView text_pwt;
            @BindView(R.id.text_accumulation)
            public TextView text_accumulation;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                GoodsListData data = mListBean.getList().get(position);
                text_name.setText(""+data.getGna());
                text_weight.setText(""+data.getGwt());
                text_price.setText(""+data.getGpr());
                text_money.setText(""+MathUtils.multiply(""+data.getGpr(),""+data.getGwt()));
                text_accumulation.setText(""+data.getAcc());
                MyUtils.setNotNullText(text_pwt,data.getPwt());
//                img_icon.setImageResource(data.getImgSrcByFsg());
                BasisApp.loadImg(mContext,MyHttpUtils.getAbsoluteUrl("/leaf"+data.getPath()),img_icon,R.mipmap.icon_tea_green);
                if(data.isCheck()){
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_blue_bg_corner));
                }else {
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_green_line_corner));
                }

                if(data.isGuadan()){
                    text_gua.setVisibility(View.VISIBLE);
                }else {
                    text_gua.setVisibility(View.GONE);
                }
                list_item.setTag(data);
                btn_kou.setTag(data);
                btn_chen.setTag(data);
                btn_add.setTag(data);
                img_change.setTag(data);
            }
            @OnClick(R.id.list_item)
            void onItemClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                data.setCheck(!data.isCheck());
                notifyItemChanged(getAdapterPosition());

            }

            @OnClick(R.id.btn_kou)
            void onKouClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                DialogUtils.showEditNumberDialog(mContext,"提示","请输入扣重", "确定", new DialogUtils.TextResult() {
                    @Override
                    public void resultText(String text) {
                        data.setGwt(MathUtils.subtract(data.getGwt(),text));
                        data.setPwt(MathUtils.add(data.getPwt(),text));
                        notifyItemChanged(getAdapterPosition());
                        notifyBottonText();
                    }
                });
            }


            @OnClick(R.id.btn_chen)
            void onChenClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                DialogUtils.showEditNumberDialog(mContext,"提示","请输入去皮数量(默认为1)", "确定", new DialogUtils.TextResult() {
                    @Override
                    public void resultText(String text) {
                        data.setGwt(MathUtils.subtract(data.getGwt(),MathUtils.multiply(text,presenter.getScaleWeight())));
                        data.setPwt(MathUtils.add(data.getPwt(),MathUtils.multiply(text,presenter.getScaleWeight())));
                        notifyItemChanged(getAdapterPosition());
                        notifyBottonText();
                    }
                });
            }

            @OnClick(R.id.btn_add)
            void onGuaDanClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                DialogUtils.showWarningDialog(mContext,"是否累加？","累加",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        data.setGwt(MathUtils.add(data.getGwt(),presenter.getScaleWeight()));
                        data.setAcc(data.getAcc()+1);
//                        DialogUtils.showSuccessrDialog(sDialog,"累加成功","总重量：" +data.getGwt(),"确定");
                        sDialog.dismiss();
                        showToast("累加成功,"+"总重量：" +data.getGwt());
                        notifyItemChanged(getAdapterPosition());
                        notifyBottonText();
                    }
                });
            }

            @OnClick(R.id.img_change)
            void onChangeClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                String[] type = getResources().getStringArray(R.array.tea_type);

                DialogUtils.showMenuDialog(mContext, type, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();   
                        needChangePosition = getAdapterPosition();
                        switch (type[which]){
                            case Constants.YZ:        //银针按钮
                                presenter.getGoodsListByFsg(ScaleActivity.this,Constants.YZ);
                                break;
                            case Constants.SM:        //寿眉按钮
                                presenter.getGoodsListByFsg(ScaleActivity.this,Constants.SM);
                                break;
                            case Constants.MD:      //牡丹按钮
                                presenter.getGoodsListByFsg(ScaleActivity.this,Constants.MD);
                                break;
                        }
                    }
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == Constants.QCORDRESULT) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    DialogUtils.showSuccessrDialog(mContext,"解析结果",result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    DialogUtils.showErrorDialog(mContext,"解析二维码失败");
                }
            }
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            //当isShouldHideInput(v, ev)为true时，表示的是点击输入框区域，则需要显示键盘，同时显示光标，反之，需要隐藏键盘、光标
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    //处理Editext的光标隐藏、显示逻辑
                    edit_price.clearFocus();
                    edit_md.clearFocus();
                    edit_yz.clearFocus();
                    edit_sm.clearFocus();
                    edit_code.clearFocus();
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }




}
